package com.fbli.scoket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/***
 * 服务端
 */
public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听，等待连接
        //要求在本机没有其他服务在监听9999oc
        //这个serverSocket 可以通过accept()返回多个Socket[多并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听，等待连接..");
        //2.当没有客户端连接9999端口时，程序会阻塞，等待连接
        //如果有客户端连接，则会返回Scoket对象，程序继续
        Socket socket= serverSocket.accept();
        System.out.println("socket =" + socket);
        //3.通过socket.getInputStream()读取,客户端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        //4.io读取，使用字符流,使用转换流将inputStream转成字符流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
        //使用字符输出流方式回复信息
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,client 字符流");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        //结束写入标记
        //socket.shutdownOutput();
        //关闭流和socket
        bufferedWriter.close();
        bufferedReader.close();//关闭外层流
        socket.close();
        serverSocket.close();
        System.out.println("服务端关闭");
    }
}
